import type { HttpResponse, HttpTask, HttpError } from 'luch-request';
import { toast } from '@/utils';
enum ErrMsgEnum {
  'request:fail timeout' = '请求超时,请稍后重试',
  'request:fail' = '网络错误,请稍后重试'
}

/**
 * 请求结果错误处理
 */
export const handleError = (response: HttpResponse<any, HttpTask> | HttpError<any, HttpTask>) => {
  console.log(response);

  const custom = response.config?.custom;
  const data = response.data;
  // 如果没有显式定义custom的toast参数为false的话，默认对报错进行toast弹出提示
  if (custom?.showErrorToast !== false) {
    const message = ErrMsgEnum[response.errMsg] || data?.message || '服务器错误,请联系管理';

    toast.warning(message);
  }
  // 如果需要catch返回，则进行reject
  if (custom?.catch) {
    return Promise.reject(data);
  } else {
    // 否则错误
    return { error: ErrMsgEnum[response.errMsg] || data?.message || '服务器错误,请联系管理员' };
  }
};
